//
//  CZPublishViewController.swift
//  git
//
//  Created by 徐 鹏超 on 16/4/14.
//  Copyright © 2016年 徐 鹏飞. All rights reserved.
//

import UIKit

let CZChoosePictureViewMargin: CGFloat = 10
let CZChoosePictrueWH = kUIScreenWidth - 2 * CZChoosePictureViewMargin

class CZPublishViewController: UIViewController,UIImagePickerControllerDelegate,UINavigationControllerDelegate {

    override func loadView() {
        super.loadView()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = UIColor.grayColor()
        
        view.addSubview(textView)
        view.addSubview(toolBar)
        
        setupNav()
        setupTextView()
        setupToolBar()
        
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "changeHolder", name: UITextViewTextDidChangeNotification, object: nil)

        NSNotificationCenter.defaultCenter().addObserver(self, selector: "changeToolBar:", name: UIKeyboardWillChangeFrameNotification, object: nil)

        // 接收表情的通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "showEmoticon:", name: kNotificationEmoticon, object: nil)
    }
    
    //MARK:-- 表情键盘的通知
    @objc private  func showEmoticon(noti: NSNotification){
        
        if let emoticon = noti.userInfo?["emoticon"] as? CZEmoticon{
            
            // 设置表情图片
            if let png = emoticon.png {
                
                // 问题: 原来的表情和文字 被现在的覆盖了
                // 先保存原来的 attributedText, 因为表情附近保存在 attributedText,而没有保存在TextView
                let muattributeText = NSMutableAttributedString(attributedString: textView.attributedText)//textView.attributedText
                
                //                print(textView.text)
                //
                //                print(textView.attributedText)
                
                // 1. 创建一个 <#T##NSTextAttachment#> 实例
                let attachment = NSTextAttachment()
                // 2. 设置附件的图片
                //            let imagePath = "包的路径+图片的名字"
                let imagePath = "\(emoticon.path!)/\(png)"
                attachment.image = UIImage(named: imagePath)
                // 我想按照 Label的字体大小
                let width = textView.font?.lineHeight
                // 设置图片的大小 -- bunds与frame
                attachment.bounds = CGRectMake(0, -4, width!, width!)
                // 图片可以以 附件的形式,添加到 NSAttributedString
                let ImageAttribuet = NSAttributedString(attachment: attachment)
                
                // 获取光标的位置
                let range = textView.selectedRange
                // 把图片的 attribute替换到光标所在的位置
                muattributeText.replaceCharactersInRange(range, withAttributedString: ImageAttribuet)
                
                // 在这里拼接
                //                muattributeText.appendAttributedString(ImageAttribuet)
                // 统一所有表情和文字的大小, 设置 font
                muattributeText.addAttributes([NSFontAttributeName: textView.font!], range: NSMakeRange(0, muattributeText.length))
                
                
                textView.attributedText = muattributeText
                
                // 改变光标的位置,在原来的位置上 +1
                //  loc: 光标所在的位置
                // len: 光标选择的长度
                textView.selectedRange = NSMakeRange(range.location+1, 0)
                
                
            }
            
            // 设置emoji
            if let emoji = emoticon.emoji {
                
                // range: 光标所在的位置
                // withText: 要替换的String
                if let range = textView.selectedTextRange{
                    
                    textView.replaceRange(range, withText: emoji)
                }
                
                
            }
            
        }
        
        
    }
    
    override func viewWillDisappear(animated: Bool) {
        super.viewWillDisappear(animated)
        
        textView.resignFirstResponder()
        
        //        textView.setNeedsLayout()
    }
    
    
    //MARK:--导航视图[中间的title是个难点]
    private func setupNav(){
        
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", style: UIBarButtonItemStyle.Plain, target: self, action: "dismiss")
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发布", style: UIBarButtonItemStyle.Plain, target: self, action: "publish")
        
        navigationItem.rightBarButtonItem?.enabled = false
        
        
        // 中间的title是个难点
        //        navigationItem.title = "发布微博\nitcast" 找了半天失败了, \n 可以在Label里换行
        
        let titleView = UILabel(frame: CGRectMake(0,0,200,44))
        
        //
        let str  = "发布微博\nitcast"
        titleView.numberOfLines = 0
        
        // 居中
        titleView.textAlignment = .Center
        
        /*
        NSString  --不可变
        NSMutableString -- 可变
        
        NSAttributedString      -- 不可以修改属性
        NSMutableAttributedString -- 可以修改属性
        */
        // 1.
        let attribute = NSMutableAttributedString(string: str)
        // 2. 设置属性
        // 这个方法能够添加多个属性
        // 第一个参数:
        attribute.addAttributes([NSFontAttributeName: UIFont.systemFontOfSize(15),NSForegroundColorAttributeName: UIColor.darkGrayColor()], range: NSMakeRange(0, 4))
        attribute.addAttributes([NSFontAttributeName: UIFont.systemFontOfSize(13),NSForegroundColorAttributeName: UIColor.orangeColor()], range: NSMakeRange(4, attribute.length - 4))
        // 3
        titleView.attributedText = attribute
        
        navigationItem.titleView = titleView
        
    }

    
    //MARK:-- 导航控制的方法
    @objc private func dismiss(){
        
        dismissViewControllerAnimated(true) { () -> Void in
            
        }
    }
    
    @objc private func publish(){
        
        
        
    }
    
    
    
    
    
    //MARK:-- TextView
    private func setupTextView(){
        
        
        
        textView.snp_makeConstraints { (make) -> Void in
            make.left.equalTo(view.snp_left)
            make.top.equalTo(view.snp_top)
            make.right.equalTo(view.snp_right)
//            make.bottom.equalTo(view.snp_bottom)
            make.bottom.equalTo(toolBar.snp_top)
        }
        
        textView.font = UIFont.systemFontOfSize(15)
        
        textView.holderString = "分享新鲜事... ..."
        
        // 输入框和键盘相关的都想到 - keyboard
        // 当拖拽TextView的时候,键盘消失,只显示这个属性不可以
        textView.keyboardDismissMode = .OnDrag
        // 也需要设置textView的滚动为 垂直
        textView.alwaysBounceVertical = true
        
        textView.addSubview(chooseView)
        
        // 水平居中,宽高,距离顶部
        chooseView.snp_makeConstraints { (make) -> Void in
            
            make.top.equalTo(textView.snp_top).offset(100)
            make.centerX.equalTo(textView.snp_centerX)
            make.width.height.equalTo(CZChoosePictrueWH)
            
        }
        
        //        textView.delegate
    }
    
    //MARK:--
    @objc private func changeHolder(){
        
        // 判断有没有文字
        if textView.hasText() {
            textView.holderString = ""
            navigationItem.rightBarButtonItem?.enabled = true
        } else {
            textView.holderString = "分享新鲜事... ..."
            navigationItem.rightBarButtonItem?.enabled = false
        }
        
        
        // 视图重绘了, 需要手动调用一个方法
        textView.setNeedsDisplay()
    }
    
    
    
    //MARK:-- 键盘改变的通知
    @objc private func changeToolBar(noti: NSNotification){
        // 注意 打印信息,不是 打印发送通知的对象
        printLog(noti.userInfo)
        /*
        
        */
        
        /*  键盘弹出来的时候的通知信息
        UIKeyboardFrameEndUserInfoKey: NSRect: {{0, 465}, {414, 271}},
        UIKeyboardAnimationDurationUserInfoKey: 0.25
        
        键盘退出时候的通知信息
        UIKeyboardFrameEndUserInfoKey: NSRect: {{0, 736}, {414, 271}}
        */
        
        
        /*
        
        if 键盘弹出来的时候 {
        toolBar.snp_updateConstraints { (make) -> Void in
        make.bottom.equalTo(view.snp_bottom).offset(271)
        }
        } else if 键盘退出的时候 {
        toolBar.snp_updateConstraints { (make) -> Void in
        make.bottom.equalTo(view.snp_bottom).offset(0)
        }
        }
        
        */
        
        let rect = noti.userInfo![UIKeyboardFrameEndUserInfoKey]?.CGRectValue
        
        //        271 + 465 = 736
        if let rect = rect{
            
            if rect.origin.y == (KUIScreenHeight - rect.size.height) {
                toolBar.snp_updateConstraints { (make) -> Void in
                    make.bottom.equalTo(view.snp_bottom).offset(-rect.size.height)
                }
            } else if rect.origin.y == KUIScreenHeight {
                toolBar.snp_updateConstraints { (make) -> Void in
                    make.bottom.equalTo(view.snp_bottom).offset(0)
                }
            }
        }
        
        let duration = noti.userInfo![UIKeyboardAnimationDurationUserInfoKey]?.doubleValue
        UIView.animateWithDuration(duration!) { () -> Void in
            
            self.toolBar.layoutIfNeeded()
            
        }
        
    }

    //MARK:-- 按钮的点击方法
    @objc private func choosePicture(){
        // 相册选择以及照相机的选择
        /*
        case PhotoLibrary
        case Camera
        case SavedPhotosAlbum // 范围小了,只有moments
        UIImagePickerController 支持这3种类型
        
        选择图片的类型
        sourceType: UIImagePickerControllerSourceType // default value is UIImagePickerControllerSourceTypePhotoLibrary.
        
        
        */
        let picture = UIImagePickerController()
        
        // 类型选择相机的时候,一定要检测一下相机的可用性
        picture.sourceType = .SavedPhotosAlbum //
        
        // 设置一下代理
        // 它的2个协议都要遵守
        picture.delegate = self
        
        presentViewController(picture, animated: true) { () -> Void in
            
        }

    }
    
    @objc private func inputEmoticon(){
        let emotiocn = CZEmoticonView()
        
        emotiocn.frame = CGRectMake(0, 0, kUIScreenWidth, 216)
        
//        emotiocn.backgroundColor = UIColor.lightGrayColor()
        
        print(textView.inputView)
        
        if textView.inputView == nil {
            textView.inputView = emotiocn
        } else {
            textView.inputView = nil
        }
        // 显示表情视图
        //        textView.inputView = emotiocn
        // inputView 默认没有, 点一下为 nil的时候,显示emotion
        // 有emoticon的时候,再点击, 变成 nil
        
        // 切换到键盘的时候,让  inputView = nil
        // 切换到 表情的时候, inputView = emotiocn
        // 有一个方法
        textView.reloadInputViews()
        textView.becomeFirstResponder()
    }
    
    

    
    //MARK:-- UIToolbar
    private func setupToolBar(){
        toolBar.backgroundColor = UIColor.darkGrayColor()
        
        // 左,右,下,高
        toolBar.snp_makeConstraints { (make) -> Void in
            
            make.left.equalTo(view.snp_left)
            make.right.equalTo(view.snp_right)
            make.bottom.equalTo(view.snp_bottom)
            make.height.equalTo(44)
            
        }
        
        // 注意你 添加了一个视图的约束,要注意他周边的视图有没有影响
        // 1. 初始化一个数组用于盛放items
        var items: [UIBarButtonItem] = [UIBarButtonItem]()
        
        let itemSettings = [["imageName": "compose_toolbar_picture", "action": "choosePicture"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background", "action": "inputEmoticon"],
            ["imageName": "compose_addbutton_background"]]
        // 一般 个人设置里或者一些固定的页面里,我们可以采用上边的形式
        
        // 2.通过遍历来实现 UIBarButtonItem
        for item in itemSettings{
            
            // 由于按钮的点击需要有高亮效果,所以我们采用自定义View -> UIButton
            let button = UIButton(type: UIButtonType.Custom)
            
            
            button.setImage(UIImage(named: item["imageName"]!), forState: UIControlState.Normal)
            //
            let name = item["imageName"]!
            button.setImage(UIImage(named: "\(name)_highlighted"), forState: UIControlState.Highlighted)
            
            // 设置大小
            button.sizeToFit()
            
            // 按钮的点击事件
            if let action = item["action"] {
                // 注意: 按钮的方法是 Selector ,并不是 字符串
                button.addTarget(self, action: Selector(action), forControlEvents: UIControlEvents.TouchUpInside)
            }
            
            let barButtonItem = UIBarButtonItem(customView: button)
            
            items.append(barButtonItem)
            // 添加弹簧,把控件分割开
            items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
        }
        // 删除最后一个
        items.removeLast()
        
        toolBar.items = items
        
    }
    
    

    
    
    
    
    
    
    
    deinit{
        //        NSNotificationCenter.defaultCenter().removeObserver(self, name: UITextViewTextDidBeginEditingNotification, object: nil)
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    
    //MARK:-- 懒加载
    private lazy var textView: CZTextView = CZTextView()
    
    
    private lazy var toolBar: UIToolbar = UIToolbar()
    
    
    private lazy var chooseView: CZChoosePictureView = {
        
        let choose = CZChoosePictureView()
        
        // 闭包作为一个参数,进行传值,然后会进行回调
        // 闭包会对 里边的 变量 进行一个强引用
        // 闭包对 self有一个强引用
        // self 对 chooseView强应用
        // chooseView强引用了闭包
        
        // 打破强引用
        // [weak self] ->  self?.choosePicture()
        //  [unowned self] -> self.choosePicture()
        // weak var typeSelf = self -> self.choosePicture()
        // oc
        weak var typeSelf = self
        
        let closure1 = { [unowned self] ()->() in
            
            printLog("回调")
            self.choosePicture()
            
        }
        
        choose.closure = closure1
        
        return choose
        
        
    }()
    
}

extension CZPublishViewController{
    
    //已经废弃了,但是还可以使用,如果选择实现了这个方法,最好把 imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) 注释掉
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        
        
        //        chooseView.images.removeAll()
        //
        //        //不建议大家这么做,把里边的属性 私有
        //        chooseView.images.append(image)
        //
        //        chooseView.reloadData()
        // 为外尽量提供少的属性,多提供方法,然后把一些功能实现尽量私有化,然后让自定的视图去实现
        chooseView.addImage(image)
        
        picker.dismissViewControllerAnimated(true) { () -> Void in
            
        }
        
    }
    
    // 一旦实现了代理协议,一定要用代码实现消失方法
    //    @available(iOS 2.0, *)
    //    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]){
    //
    //       printLog(info)
    //        /*
    //        ["UIImagePickerControllerMediaType": public.image,
    //        "UIImagePickerControllerOriginalImage": <UIImage: 0x7fd2c7802040> size {3000, 2002} orientation 0 scale 1.000000,
    //        "UIImagePickerControllerReferenceURL": assets-library://asset/asset.JPG?id=9A9E11AE-D36A-40BE-8C4F-9019C8E9E693&ext=JPG]
    //
    //        */
    //        picker.dismissViewControllerAnimated(true) { () -> Void in
    //
    //        }
    //
    //    }
    @available(iOS 2.0, *)
    func imagePickerControllerDidCancel(picker: UIImagePickerController){
        
        picker.dismissViewControllerAnimated(true) { () -> Void in
            
        }
        
        
    }
    
}











